package com.compty.paint.web.member;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.math.RandomUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Criteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

import com.compty.core.framework.image.ImageUtils;
import com.compty.core.framework.util.FileUtil;
import com.compty.core.framework.util.StringUtil;
import com.compty.core.page.Page;
import com.compty.core.struts2.BaseAction;
import com.compty.core.utils.CommonsUtil;
import com.compty.paint.domain.Auction;
import com.compty.paint.domain.AuditState;
import com.compty.paint.domain.ImageInfo;
import com.compty.paint.domain.LogInfo;
import com.compty.paint.domain.ProvinceInfo;
import com.compty.paint.domain.UploadState;
import com.compty.paint.domain.support.LogTypeEnum;
import com.compty.paint.manager.AuctionManager;
import com.compty.paint.manager.AuditStateManager;
import com.compty.paint.manager.ImageInfoManager;
import com.compty.paint.manager.LogInfoManager;
import com.compty.paint.manager.ProvinceInfoManager;
import com.compty.paint.manager.UploadStateManager;
import com.compty.paint.util.Constants;
import com.compty.security.domain.User;

/**
 *拍卖预展Action
 */
public class AuctionAction extends BaseAction<Auction>{

	private static final long serialVersionUID = 2387081835313158086L;
    private static Log logger = LogFactory.getLog(AuctionAction.class);
	
	private ProvinceInfoManager provinceInfoManager;
	private AuctionManager auctionManager;
	private AuditStateManager auditStateManager;
	private UploadStateManager uploadStateManager;
	private LogInfoManager logInfoManager;
	private ImageInfoManager imageInfoManager;
	
	private Auction auction;
	private List<ProvinceInfo> provinceInfoList;
	private Date startDate;
	private Date endDate;
	private String operateStr; //1表示隐藏,2表示删除,3：审核通过 ,4:审核驳回,5:显示
	private File myFile;
	private String fileName;//图片原始名字
	
    public void setMyFileFileName(String fileName)  {
        this.fileName = fileName;
    }
    
    public String getFileName() {
		return fileName;
	}
       
    public File getMyFile() {
		return myFile;
	}

	public void setMyFile(File myFile)  {
        this.myFile = myFile;
    } 

	public void setImageInfoManager(ImageInfoManager imageInfoManager) {
		this.imageInfoManager = imageInfoManager;
	}
	
	/**
	 *@Todo:新增预处理
	 *@CreateTime:2011-6-9 下午05:05:07
	 */
	public String addPrepare(){
		
		this.auction = null;
		
		this.provinceInfoList = provinceInfoManager.getAll();
		
		return "addPrepare";
	}
	
	/**
	 *@Todo:保存拍卖基本资料
	 *@CreateTime:2011-6-9 下午08:12:37
	 * @throws IOException
	 */
	public String save() throws Exception{
		
		if( auction != null){
			User userInfo = (User) session.getAttribute(Constants.Userinfo);
			auction.setEntryPerson(userInfo);
			auction.setUploadTime(Calendar.getInstance().getTime());
			auction.setModifyTime(Calendar.getInstance().getTime());
			
			if(Constants.Auto_Audit){
				AuditState auditState = auditStateManager.findUniqueBy("english_name",Constants.Audit_State_Pass);
				auction.setAuditState(auditState);
			}else{
				AuditState auditState = auditStateManager.findUniqueBy("english_name",Constants.Audit_State_Init);
				auction.setAuditState(auditState);
			}
			
			UploadState  uploadState = uploadStateManager.findUniqueBy("english_name", Constants.Upload_State_Init); //上传状态，是否锁定，隐藏等
			auction.setUploadState(uploadState);
			
			if(auction.getProvinceInfo() == null || auction.getProvinceInfo().getId()== null){
				auction.setProvinceInfo(null);
			}
			if(auction.getCityInfo() == null || auction.getCityInfo().getId() == null ){
				auction.setCityInfo(null);
			}
			
			auctionManager.save(auction);
			generateImageOfAuctionAfterSaved(auction);//第一次生成图片
			
			LogInfo logInfo = buildLogInfo(LogTypeEnum.addAuction, "保存拍卖"+auction.getName()+"基本资料成功");
			logInfoManager.writeLog(logInfo);
		}
		
		return "saved";
	}
	
	/**
	 *@Todo:ajax提交保存
	 * @throws IOException
	 */
	@SuppressWarnings("unchecked")
	public String save_additional() throws Exception{
		
		if( auction != null){
			User userInfo = (User) session.getAttribute(Constants.Userinfo);
			auction.setEntryPerson(userInfo);
			auction.setUploadTime(Calendar.getInstance().getTime());
			auction.setModifyTime(Calendar.getInstance().getTime());
			
			if(Constants.Auto_Audit){
				AuditState auditState = auditStateManager.findUniqueBy("english_name",Constants.Audit_State_Pass);
				auction.setAuditState(auditState);
			}else{
				AuditState auditState = auditStateManager.findUniqueBy("english_name",Constants.Audit_State_Init);
				auction.setAuditState(auditState);
			}
			
			UploadState  uploadState = uploadStateManager.findUniqueBy("english_name", Constants.Upload_State_Init); //上传状态，是否锁定，隐藏等
			auction.setUploadState(uploadState);
			
			if(auction.getProvinceInfo() == null || auction.getProvinceInfo().getId()== null){
				auction.setProvinceInfo(null);
			}
			if(auction.getCityInfo() == null || auction.getCityInfo().getId() == null ){
				auction.setCityInfo(null);
			}
			
			Long auction_Id = auction.getId();
			Page p = auctionManager.findImageInfosByAuctionId(1,10000,auction_Id);
			List imagesInfo = (List) p.getResult();
			auction.setImagesInfo(imagesInfo);
			
			auctionManager.save(auction);
			generateImageOfAuctionAfterSaved(auction);//第一次生成图片
			
			LogInfo logInfo = buildLogInfo(LogTypeEnum.addAuction, "保存拍卖"+auction.getName()+"基本资料成功");
			logInfoManager.writeLog(logInfo);
			
			request.setAttribute("ajaxData", "0000");
		}
		
		return "save_additional";
	}
	
	/**
	 *@Todo:修改
	 *@CreateTime:2011-8-15 下午04:45:08
	 */
	public String modifyPrepare(){
		
		this.provinceInfoList = provinceInfoManager.getAll();
		
		if( auction != null){
			Long id = auction.getId();
			this.auction = auctionManager.get(id);
		}
		
		return "modifyPrepare";
	}

	/**
	 * 修改画家信息
	 *@CreateTime:2011-6-9 上午10:19:01
	 * @return
	 */
	public String modify() throws Exception{
		
		if(auction != null){
			
			auction.setModifyTime(Calendar.getInstance().getTime());
			auctionManager.save(auction);
			generateImageOfAuctionAfterSaved(auction);//第一次生成图片
			
			LogInfo logInfo = buildLogInfo(LogTypeEnum.modifyAuction, "修改拍卖"+auction.getName()+"基本资料");
			logInfoManager.writeLog(logInfo);
		}
		
		return "modified";
	}
	
	/**
	 * 显示艺术家详情及作品信息
	 *@CreateTime:2011-8-3 上午09:55:23
	 * @return
	 */
	public String showDetail(){
		
		if(auction != null){
			
			Long id = auction.getId();
			this.auction = auctionManager.get(id);
			this.page = auctionManager.findImageInfosByAuctionId(curPage,20,id);
		}
		
		return "showDetail";
	}
	
	/**
	 *@Todo:修改状态
	 *@CreateTime:2011-6-9 上午10:19:17
	 */
	public String changeUploadState(){
		
		if(auction != null){
			Long id = auction.getId();
			this.auction = auctionManager.get(id);
			
			if("1".equals(operateStr)){ //隐藏
				UploadState  uploadState = uploadStateManager.findUniqueBy("english_name",Constants.Upload_State_Hidden);
				auction.setUploadState(uploadState);
				auction.setModifyTime(Calendar.getInstance().getTime());
				auctionManager.save(auction);
				
				LogInfo logInfo = buildLogInfo(LogTypeEnum.modifyAuction, "修改拍卖"+auction.getName()+"基本信息,operate：隐藏");
				logInfoManager.writeLog(logInfo);
				
			}else if("2".equals(operateStr)){//删除
				auctionManager.removeById(id);
				
				LogInfo logInfo = buildLogInfo(LogTypeEnum.deleteExhibition, "删除拍卖"+auction.getName()+"基本信息");
				logInfoManager.writeLog(logInfo);
			}
			else if("3".equals(operateStr)){
				AuditState auditState = auditStateManager.findUniqueBy("english_name", Constants.Audit_State_Pass);  //审核通过
				auction.setAuditState(auditState);
				auction.setModifyTime(Calendar.getInstance().getTime());
				auctionManager.save(auction);
				
				LogInfo logInfo = buildLogInfo(LogTypeEnum.audit_pass_Auction, "审核通过拍卖"+auction.getName());
				logInfoManager.writeLog(logInfo);
			}
			else if("4".equals(operateStr)){
				AuditState auditState = auditStateManager.findUniqueBy("english_name", Constants.Audit_State_Overrule);  //审核驳回
				auction.setAuditState(auditState);
				auction.setModifyTime(Calendar.getInstance().getTime());
				auctionManager.save(auction);
				
				LogInfo logInfo = buildLogInfo(LogTypeEnum.audit_overrule_Auction, "审核驳回拍卖"+auction.getName());
				logInfoManager.writeLog(logInfo);
			}
			else if("5".equals(operateStr)){//显示
				UploadState uploadState = uploadStateManager.findUniqueBy("english_name", Constants.Upload_State_Init);
				auction.setUploadState(uploadState);
				auction.setModifyTime(Calendar.getInstance().getTime());
				auctionManager.save(auction);
				
				LogInfo logInfo = buildLogInfo(LogTypeEnum.modifyAuction, "修改拍卖"+auction.getName()+"基本信息,operate：显示");
				logInfoManager.writeLog(logInfo);
			}
		}
		
		request.setAttribute("ajaxData", "0000");
		
		return "changState";
	}
	
	/**
	 * 列出所有拍卖(分页显示)
	 */
	public String list(){
		
		 Criteria criteria;
		  
        if (sort != null) {
            boolean isAsc = dir.equalsIgnoreCase("asc");
            criteria = auctionManager.createCriteria(sort, isAsc);
        } else {
            criteria = auctionManager.createCriteria();
        }
        
        criteria.addOrder(Order.desc("id"));
        
        User userInfo = (User) session.getAttribute(Constants.Userinfo);
        if(userInfo!= null && "0".equals(userInfo.getAdministratorFlag())){
        	  criteria = criteria.add(Restrictions.eq("entryPerson", userInfo));
        }
        
        if(startDate != null){
        	 criteria = criteria.add(Restrictions.ge("uploadTime", startDate));
        }
        
        if(endDate != null){
        	 criteria = criteria.add(Restrictions.lt("uploadTime", endDate));
        }

        if ((filterTxt != null) && (filterValue != null)
                && (!filterTxt.equals("")) && (!filterValue.equals(""))) {
            criteria = criteria.add(Restrictions.like(filterTxt,
                        "%" + filterValue + "%"));
        }

        this.page = auctionManager.pagedQuery(criteria, curPage, pageSize);
        
        return "list";
	}
	
	/**
	 *@Todo:列出拍卖预展基本信息及画册图片
	 *@CreateTime:2011-8-21 上午08:24:19
	 * @return
	 */
	public String listImagesByAuction(){
		
		String auction_IdStr = request.getParameter("auction_Id");
		Long auctionId = Long.valueOf(auction_IdStr);
		
		this.auction = auctionManager.get(auctionId);
		
		if( auction != null){
			this.page = auctionManager.findImageInfosByAuctionId(curPage,20,auctionId);
		}
		
		return "listImagesByAuction";
	}
	
	/**
	 *@Todo:TODO上传画册图片
	 *@CreateTime:2011-8-21 上午11:37:36
	 * @return
	 * @throws IOException
	 */
	public String uploadImages() throws IOException{
		
		if (myFile != null) {
			
			try {
				String  memo = request.getParameter("memo");
				String indexFlag = request.getParameter("indexFlag");
				
				long filenameExclude = RandomUtils.nextInt();
				String imageFileName = filenameExclude + "."+ StringUtil.getExt(fileName) ;
				String srcpath = getImageUploadPath()+ CommonsUtil.getPathSymbol() + imageFileName;
				File imageFile = new File(srcpath);
				
				FileUtil.copy(myFile, imageFile);
				
				ImageInfo imageInfo = saveImageToDB(imageFile, fileName, "10"); 
				logger.debug("Id:"+imageInfo.getId()+"=======suffix:"+imageInfo.getSuffix());
				
				imageInfo.setMemo(memo);
				if("yes".equals(indexFlag)){//索引图片，特殊标识
					imageInfo.setSharpId(100l);
				}
				
				String  auctionIdStr = request.getParameter("id");
				Long auctionId = Long.valueOf(auctionIdStr);
				this.auction = auctionManager.get(auctionId);
				
				auction.getImagesInfo().add(imageInfo);
				auctionManager.save(auction);
				
				LogInfo logInfo = buildLogInfo(LogTypeEnum.modifyAuction, "上传拍卖"+auction.getName()+"画册图片");
				logInfoManager.writeLog(logInfo);
				
				imageFile.delete();
			} catch (NumberFormatException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}
        }
		
		return SUCCESS;
	}
	
	/**
	 *@Todo:修改画册图片
	 *@CreateTime:2011-8-26 下午05:27:06
	 * @throws IOException
	 */
	public String modifyImages() throws IOException{
		
		if (myFile != null) {
			try {
				String  imageIdStr = request.getParameter("imageId");
				String  memo = request.getParameter("memo");
				String indexFlag = request.getParameter("indexFlag");
				
				long filenameExclude = RandomUtils.nextInt();
				String imageFileName = filenameExclude + "."+ StringUtil.getExt(fileName) ;
				String srcpath = getImageUploadPath()+ CommonsUtil.getPathSymbol() + imageFileName;
				File imageFile = new File(srcpath);
				FileUtil.copy(myFile, imageFile);
				
				ImageInfo imageInfo = buildImageInfo(imageFile, fileName, "10"); 
				Long imageId = Long.valueOf(imageIdStr);
				imageInfo.setId(imageId);
				imageInfo.setMemo(memo);
				if("yes".equals(indexFlag)){//索引图片，特殊标识
					imageInfo.setSharpId(100l);
				}
				
				imageInfoManager.save(imageInfo);
				
				logger.debug("Id:"+imageInfo.getId()+"=======suffix:"+imageInfo.getSuffix());
				
				String  auctionIdStr = request.getParameter("id");
				Long auctionId = Long.valueOf(auctionIdStr);
				this.auction = auctionManager.get(auctionId);
				
				LogInfo logInfo = buildLogInfo(LogTypeEnum.modifyAuction, "修改拍卖"+auction.getName()+"画册图片");
				logInfoManager.writeLog(logInfo);
				
				imageFile.delete();
				
			} catch (NumberFormatException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
			
		return "modifyImages";
	}
	
	/**
	 * 删除画册图片
	 */
	public String deleteImage(){
		
		String  imageIdStr = request.getParameter("imageId");
		Long imageId = Long.valueOf(imageIdStr);
		
		String  auctionIdStr = request.getParameter("id");
		Long auctionId = Long.valueOf(auctionIdStr);
		
		auctionManager.deleteImage(imageId,auctionId);
		
		this.auction = auctionManager.get(auctionId);
		
		LogInfo logInfo = buildLogInfo(LogTypeEnum.modifyAuction, "删除拍卖"+auction.getName()+"画册图片");
		logInfoManager.writeLog(logInfo);
		
		return "deleteImage";
	}
	
	/**
	 *@Todo:TODO 保存图片至DB
	 * @param file 图片文件
	 * @param originalName  图片原始名字
	 * @param sharpId 图片形状类型
	 * @throws Exception 
	 */
	private ImageInfo saveImageToDB(File file,String originalName,String sharpId) throws Exception{
	    	
	    	ImageInfo imageInfo = buildImageInfo(file,originalName, sharpId);
	    	imageInfoManager.save(imageInfo);
	    	
	    	return imageInfo;
	}
	
	private ImageInfo buildImageInfo(File file,String originalName,String sharpId) throws Exception{
		FileInputStream input = null;
		try {
			String sourcePath =  file.getAbsolutePath();
			ImageUtils.scaleImage(sourcePath, sourcePath, 850.0, 0.0);
			input = new FileInputStream(file);
			ImageInfo imageInfo = new ImageInfo();
			imageInfo.setOriginalName(originalName);
			String suffix =  StringUtil.getExt(originalName);
			imageInfo.setSuffix(suffix);
			imageInfo.setSharpId(Long.valueOf(sharpId));
	    	return imageInfo;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}finally{
			if(input !=null){
				try {
					input.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		
    	return null;
	}
	
	private void generateImageOfAuctionAfterSaved(Auction auction) throws Exception{
		if( auction.getImageInfo() != null){
			ImageInfo img = imageInfoManager.get(auction.getImageInfo().getId());
			writeImg(img, Constants.AuctionFlag);
		}
	}

	public Auction getAuction() {
		return auction;
	}

	public void setAuction(Auction auction) {
		this.auction = auction;
	}

	public List<ProvinceInfo> getProvinceInfoList() {
		return provinceInfoList;
	}

	public void setProvinceInfoList(List<ProvinceInfo> provinceInfoList) {
		this.provinceInfoList = provinceInfoList;
	}

	public Date getStartDate() {
		return startDate;
	}

	public void setStartDate(Date startDate) {
		this.startDate = startDate;
	}

	public Date getEndDate() {
		return endDate;
	}

	public void setEndDate(Date endDate) {
		this.endDate = endDate;
	}

	public String getOperateStr() {
		return operateStr;
	}

	public void setOperateStr(String operateStr) {
		this.operateStr = operateStr;
	}

	public void setProvinceInfoManager(ProvinceInfoManager provinceInfoManager) {
		this.provinceInfoManager = provinceInfoManager;
	}

	public void setAuctionManager(AuctionManager auctionManager) {
		this.auctionManager = auctionManager;
	}

	public void setAuditStateManager(AuditStateManager auditStateManager) {
		this.auditStateManager = auditStateManager;
	}

	public void setUploadStateManager(UploadStateManager uploadStateManager) {
		this.uploadStateManager = uploadStateManager;
	}

	public void setLogInfoManager(LogInfoManager logInfoManager) {
		this.logInfoManager = logInfoManager;
	}
}
